<style>
* {
  user-select: none;
}
.ability {
  width: 260px;
  margin-right: 20px;
  float: right;
}
.abilityScorll {
  overflow-y: auto;
  max-height: 700px;
}
.shActive {
  color: #409eff !important;
  border-color: #c6e2ff !important;
  background-color: #ecf5ff !important;
}
.el-form-item {
  margin-bottom: 0;
}
.canvas1 {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  z-index: 15;
}
.sh-input {
  color: #409eff;
}
.sh-out {
  color: aqua;
}
</style>
<template>
  <div class="demo-content">
    <section class="demo-text">
      <h1>单线图编辑</h1>
      <el-row>
        <el-col :span="5">
          <el-tabs v-model="activeName" :stretch="true" v-if="refresh">
            <!-- <el-tab-pane label="画笔工具" name="brush">
              <el-card :body-style="{ padding: '0px' }">
                <div style="padding: 14px;">
                  <el-button-group>
                    <el-button
                      v-for="(item) in drawtypelist"
                      :type="item.type"
                      @click="draw(item.type)"
                      :class="drawtype==item.type?'shActive':''"
                      :key="item.type"
                    >{{item.name}}</el-button>
                  </el-button-group>
                </div>
                <div style="padding:14px">
                  <el-form ref="form" :model="colorList" label-width="80px">
                    <el-form-item label="边框">
                      <el-color-picker v-model="colorList.stroke" @change="changestroke"></el-color-picker>
                    </el-form-item>
                    <el-form-item label="填充">
                      <el-color-picker v-model="colorList.fill" @change="changefill"></el-color-picker>
                    </el-form-item>
                    <el-form-item label="边框宽度">
                      <el-input
                        type="number"
                        min="1"
                        v-model="colorList.strokeWidth"
                        @change="changesstrokeWidth"
                      ></el-input>
                    </el-form-item>
                  </el-form>
                </div>
              </el-card>
            </el-tab-pane>-->
            <!-- <el-tab-pane label="样式" name="style" class="abilityScorll">
              <cstyle
                v-for="item in stylelist"
                :target="activeobj"
                :name="item.name"
                :keyword="item.key"
                :type="item.type"
                :setting="item.setting"
                :Informatter="item.Informatter"
                :Outformatter="item.Outformatter"
                :key="'s'+item.key"
              ></cstyle>
              <el-button>保存</el-button>
            </el-tab-pane>-->
            <el-tab-pane label="单线图列表" name="maplist" class="abilityScorll">
              <el-row v-for="(key,value) in maplist" :key="value" style="margin:5px">
                <el-button style="width:100%" @click="loadfile(value)">{{value}}</el-button>
              </el-row>
            </el-tab-pane>
            <el-tab-pane label="设备属性" name="attr" class="abilityScorll" v-if="testonce">
              <div v-if="activeobj">
                <el-tag>基本属性</el-tag>
                <el-form ref="attForm" :model="activeobj">
                <el-form-item v-for="item in deviceBaseinfo" :key="item.name" :label="item.name">
                  <el-input :placeholder="'请输入'+item.name" v-model="activeobj[item.value]" @input="deviceBaseinfoInput($event,activeobj,item.value)" size="medium" class="ability"></el-input>
                </el-form-item>
              </el-form>
              <el-tag>设备属性</el-tag>
              <el-form ref="attForm" :model="deviceinfo">
                <el-form-item v-for="item in deviceinfo" :key="item.name" :label="item.name">
                  <el-input :placeholder="'请输入'+item.name" v-model="item.value" size="medium" class="ability"></el-input>
                </el-form-item>
              </el-form>
              </div>

            </el-tab-pane>
            <el-tab-pane label="设备图元" name="devicelist" class="abilityScorll">
              <el-row>
                <el-col
                  :span="5"
                  :offset="1"
                  v-for="(key,value) in devicelist"
                  :key="value"
                  style="height:150px; position: relative;"
                >
                  <el-card
                    :body-style="{ padding: '0px' ,'text-align':'center',height:'60px', background: '#f7f7f7',
    border: '1px solid #1661b9',
    'line-height': '60px','object-fit':'contain' }"
                  >
                    <img
                      style="object-fit: contain;
                          width: 100%;
                          height: 100%;
                          padding: 2px;
                          box-sizing: border-box;"
                      :src="key.src"
                      alt
                      draggable="true"
                      @dragstart="deviceDragStart($event,value)"
                      :name="value"
                    />
                  </el-card>
                  <div
                    style="position: absolute;
                            bottom: 30px;text-align:center; font-size:12px;width: 100%;"
                  >
                    <span>{{value}}</span>
                  </div>
                </el-col>
              </el-row>

              <!-- <img
                :src="url"
                alt
                draggable="true"
                ondragstart="event.dataTransfer.setData('name','柱上式断路器（通）')"
                name="柱上式断路器（通）"
              >
              <span>柱上式断路器（通）</span>-->
            </el-tab-pane>
            <el-tab-pane label="导线" name="edgelist" class="abilityScorll">
              <!-- <el-col :span="10" :offset="1">
                <el-card :body-style="{ padding: '0px' }" :class="drawtype=='edge'?'shActive':''">
                  <img src="@/imags/edge.png" alt @click="draw('edge1')" />
                  <div style="padding: 14px;" @click="draw('edge1')">
                    <span>10Kv导线</span>
                  </div>
                </el-card>
              </el-col>-->
              <el-col :span="10" :offset="1">
                <el-card :body-style="{ padding: '0px' }" :class="drawtype=='edge'?'shActive':''">
                  <img src="@/imags/edge.png" alt @click="draw('edge')" />
                  <div style="padding: 14px;" @click="draw('edge')">
                    <span>10Kv导线1</span>
                  </div>
                </el-card>
              </el-col>
              <!-- <img
                :src="url"
                alt
                draggable="true"
                ondragstart="event.dataTransfer.setData('name','柱上式断路器（通）')"
                name="柱上式断路器（通）"
              >
              <span>柱上式断路器（通）</span>-->
            </el-tab-pane>
          </el-tabs>
        </el-col>
        <el-col :span="18">
          <el-col :span="8" :offset="2">
            <el-form>
              <el-form-item label="原理图名称：">
                <el-input placeholder="请输入内容" v-model="mapname" size="medium" class="ability"></el-input>
              </el-form-item>
            </el-form>
          </el-col>

          <el-button-group>
            <!-- <el-button @click="drawstart" :class="editable?'shActive':''">开始编辑</el-button>
            <el-button @click="drawend" :class="editable?'':'shActive'">结束编辑</el-button>-->
            <el-button @click="del">删除</el-button>
            <el-button @click="link">通/断</el-button>
            <el-button @click="SaveFile">保存</el-button>
            <el-button @click="downloadfile">下载</el-button>
          </el-button-group>
          <div style="position:relative;margin:30px" ref="canvasparents" @contextmenu="contextmenu">
            <canvas id="canvas" width="1400" height="700" ref="canvas" ></canvas>
            <!-- <canvas id="canvas1" width="1200" height="600" class="canvas1"></canvas> -->
          </div>
        </el-col>
      </el-row>

      <p
        style=" display:none; text-align:right;padding-right:60px;    position: absolute;
    right: 0;
    bottom: 0;
    z-index: 9999;
    pointer-events: none;"
      >@王睿杰 2019.1.23</p>
    </section>
  </div>
</template>
<script>
/**
 * write a component's description
 * 包含了绘制插件和工具栏，等等的编辑器组件
 */
import { fabric } from "@/js/fabric";
import BaseCanvas from "@/js/staticCanvas.js";
import base from "@/js/companyBase.js";
import rluer from "@/js/rluer.js";
import history from "@/js/sc_history.js";
import interactive from "@/js/fabric.interactive.js";
import Cstyle from "./cstyle";
import {
  stylelist,
  events,
  drawtypelist,
  exportlist,
  fabricType,deviceBaseinfo
} from "./setting";
import tree from "./tree";
import {
  exportJson,
  SaveFile,
  append,
  decoration,
  loadTuopu,
  getdevice,
  saveTuopu
} from "@/js/bToa";
import { devicelist, deviceloader, createdevice } from "@/js/deviceloader";
import { maplist, maploader, createmap } from "@/js/maploader";
import alldevice from "@/js/Alldevice.js";
import allmap from "@/js/allmap.js";
import ShDevice from "@/js/suoheng.device.js";
import { ShLine, ShPolyline } from "@/js/suoheng.wires.js";
function evaltest(string) {
  try {
    return eval(string);
  } catch (e) {
    return e.message;
  }
}
export default {
  components: {
    Cstyle,
    tree
  },
  /**
   * @description 返回的数据
   * @returns {Object}
   */
  data() {
    return {
      drawtypelist, //绘制类型列表
      activeObjlist: "objlist", //左侧tab切换
      editable: true, //是否编辑状态
      canvas: null, //画布
      _clipboard: null, //粘贴板
      mouseevent: null, //复制粘贴实践
      refresh: true, //刷新控制
      devicelist, //设备图元列表
      maplist,
      deviceBaseinfo,
      colorList: {
        //颜色控制器列表
        fill: "#ff0000",
        stroke: "#002546",
        strokeWidth: 1
      }, //树状结果默认显示
      defaultProps: {
        name: "name",
        children: "_objects"
      },
      events, //监听的事件
      activeName: "devicelist", //右侧列表
      _history: null, //历史
      _start: null, //绘制开始坐标（已弃用）
      isDrawingMode: true, //是否在绘制模式（已弃用）
      _drawingobj: null, //当前正在绘制的元素对象（已弃用）
      attForm: {
        attribute: base,
        style: {}
      },
      deviceinfo: {},
      interactive: null, //交互器
      activeobj: null, //当前活跃的元素
      in1: null, //绘制器的交互区
      stylelist, //样式列表
      cmdlist: [],
      cmdinput: "",
      url: "",
      mapname: "",
      testonce: true
    };
  },
  methods: {
    deviceBaseinfoInput($event,target,attr){
      console.log($event)
    },
    contextmenu(){
        let event = window.event;
        event.stopPropagation();
        event.preventDefault();
        return false
    },
    loadfile(name) {
      this.SaveFile();
      if (maplist[name]) {
        let canvas = this.canvas;
        canvas.loadFromJSON(maplist[name], canvas.renderAll.bind(canvas));
        loadTuopu.call(canvas, maplist[name].tuopu);
        this.mapname = name;
        this.reload();
      }
    },
    SaveFile() {
      this.mapname = this.mapname || "test";
      let name = this.mapname;
      let data = this.canvas.toJSON(exportlist);
      data.name = name;
      data.tuopu = saveTuopu(this.canvas);
      maplist[name] = data;
      this.reload();
      data = decoration(JSON.stringify(data, null, "\t"), name);
      return data;
    },
    downloadfile() {
      let data = this.SaveFile();
      SaveFile(new Blob([data]), this.mapname + ".js");
    },
    deviceDragStart($event, value) {
      $event = event || window.event;
      $event.dataTransfer.setData("name", value);
    },
    /**
     * 修改边框颜色响应
     */
    /**
     * @description
     * @param {any} value
     */
    changestroke(value) {
      this.in1.setStyle("stroke", value);
    },
    /**
     * 修改填充颜色响应
     */
    /**
     * @description
     * @param {any} value
     */
    changefill(value) {
      this.in1.setStyle("fill", value);
    },
    /**
     * 修改边框宽度
     */
    /**
     * @description
     * @param {any} value
     */
    changesstrokeWidth(value) {
      this.in1.setStyle("strokeWidth", value);
    },
    link(){
    let obj = this.canvas.getActiveObject();
    if(!obj||obj.type === "activeSelection"){
        return false;
    };
      console.log(obj)
    },
    /**
     * 删除
     */
    /**
     * @description
     */
    del() {
      let obj = this.canvas.getActiveObject();
      if (!obj) {
        return;
      }
      let _this = this;
      if (obj.type === "activeSelection") {
        obj._objects.forEach(element => {
          element._sourcelist &&
            element._sourcelist.forEach(item => {
              _this.canvas.remove(item);
            });
          element._targetlist &&
            element._targetlist.forEach(item => {
              _this.canvas.remove(item);
            });
          _this.canvas.remove(element);
          this.canvas.fire("remove", { target: element });
        });
      } else {
        obj._sourcelist &&
          obj._sourcelist.forEach(item => {
            _this.canvas.remove(item);
          });
        obj._targetlist &&
          obj._targetlist.forEach(item => {
            _this.canvas.remove(item);
          });
        this.canvas.remove(obj);
        this.canvas.fire("remove", { target: obj });
      }
    },
    /**
     * 绘制，选择绘制类型
     */
    /**
     * @description
     * @param {any} type
     */
    draw(type) {
      this.canvas.chooseDrawtype(type);
    },
    /**
     * 开始编辑
     */
    /**
     * @description
     */
    drawstart() {
      this.isDrawingMode = true;
      this.canvas.draweditable(true);
      this.editable = true;
    },
    /**
     * 结束编辑
     */
    /**
     * @description
     */
    drawend() {
      this.isDrawingMode = false;
      this.canvas.draweditable(false);
      this.editable = false;
    },
    /**
     * 刷新dom
     */
    /**
     * @description
     */
    reload: function() {
      this.refresh = false;
      this.refresh = true;
    },
    /**
     * @description
     */
    clear() {
      this._clipboard = null;
      this.mouseevent = null;
    }
  },
  computed: {
    /**
     * 返回绘制类型
     */
    /**
     * @description
     * @returns {any}
     */
    drawtype() {
      if (this.canvas) {
        return this.canvas.getdrawtype();
      } else {
        return "";
      }
    },
    /**
     * 返回元素列表
     */
    /**
     * @description
     * @returns {any}
     */
    objlist() {
      return this.canvas && this.canvas._objects;
    },
    /**
     * @description
     * @returns {any}
     */
    objTojson() {
      return this.canvas && this.canvas.toDatalessJSON(exportlist, true);
    }
  },
  watch: {
    /**
     * @description
     * @param {any} newval
     * @param {any} oldval
     */
    objlist(newval, oldval) {
      this.reload();
    },
    /**
     * @description
     * @param {any} newval
     */
    activeobj(newval) {
      if (newval) {
        this.deviceinfo = newval.attr;
      } else {
        this.deviceinfo = {};
      }
    }
  },
  /**
   * 实例挂载后执行的事件
   */
  mounted() {
    let that = this;
    /**
     * 1.生成画布
     * 2.将交互器赋值给data，以便后续操作
     * 3.设置绘制类型为矩形
     * 4.设置监听事件，监听元素改变
     */
    this.$nextTick(() => {
      let canvas;

      canvas = this.canvas = new BaseCanvas("canvas");
      canvas.targetFindTolerance = 10;
      window.canvas1 = canvas;
      canvas.init();
      this._history = canvas.getHistory();
      this.interactive = canvas.getInteractor();
      this.in1 = canvas.getMaskInteractor();
      this.events.map(item => {
        canvas.on(item, function(e) {
          that.activeobj = null;
          that.activeobj = e.target || canvas.getActiveObject();
        });
      });
      canvas.on("mouse:move", function(e) {
        that.mouseevent = e;
      });
      canvas.drawEnd();
      exportlist.push("centeredScaling");
      exportlist.push("label");
      exportlist.push("did");
      function testEdge(that) {
        return !that.target || !that.source || that.source === that.target;
      }
      /*
      返回热点坐标
      */
      function gethotpost() {
        let that = this;
        return that._objects
          .filter(item => {
            return item.hotspot === true;
          })
          .map(item => {
            let point = new fabric.Point(
              item.getCenterPoint().x * that.scaleX +
                item.group.getCenterPoint().x,
              item.getCenterPoint().y * that.scaleY +
                item.group.getCenterPoint().y
            );
            point = fabric.util.rotatePoint(
              point,
              item.group.getCenterPoint(),
              fabric.util.degreesToRadians(item.group.angle)
            );
            return {
              point: point,
              name: item.hotid
            };
          });
      }

      function setLine(type) {
        let that = this;
        function cal(hotspot, point) {
          return hotspot.sort((a, b) => {
            let l1 =
              Math.pow(a.point.x - point.x, 2) +
              Math.pow(a.point.y - point.y, 2);
            let l2 =
              Math.pow(b.point.x - point.x, 2) +
              Math.pow(b.point.y - point.y, 2);
            return l1 - l2;
          });
        }
        function getpoint(type) {
          let that = this;
          if (type === "source") {
            return { x: that.x1, y: that.y1 };
          }
          if (type === "target") {
            return { x: that.x2, y: that.y2 };
          }
          return { x: 0, y: 0 };
        }
        function setpoint(point, type) {
          if (type === "source") {
            return this.set({ x1: point.x, y1: point.y });
          }
          if (type === "target") {
            return this.set({ x2: point.x, y2: point.y });
          }
          return;
        }
        function Dstop(Edeg, type) {
          var stopDevice = {
            version: "2.5.0",
            objects: [
              {
                type: "line",
                version: "2.5.0",
                originX: "left",
                originY: "top",
                left: 39.31,
                top: 27.82,
                width: 0.8,
                height: 51.43,
                fill: "blue",
                stroke: "red",
                strokeWidth: 2,
                strokeDashArray: null,
                strokeLineCap: "butt",
                strokeDashOffset: 0,
                strokeLineJoin: "miter",
                strokeMiterLimit: 4,
                scaleX: 1,
                scaleY: 1,
                angle: 0,
                flipX: false,
                flipY: false,
                opacity: 1,
                shadow: null,
                visible: true,
                clipTo: null,
                backgroundColor: "",
                fillRule: "nonzero",
                paintFirst: "fill",
                globalCompositeOperation: "source-over",
                transformMatrix: null,
                skewX: 0,
                skewY: 0,
                name: "",
                hasControls: true,
                hasBorders: true,
                perPixelTargetFind: true,
                selectable: true,
                __eventListeners: {
                  removed: [null]
                },
                centeredScaling: false,
                label: "",
                x1: 0.3990024937655825,
                x2: -0.3990024937655825,
                y1: -25.714285714285715,
                y2: 25.714285714285715
              },
              {
                type: "circle",
                version: "2.5.0",
                originX: "left",
                originY: "top",
                left: 38,
                top: 52,
                width: 6,
                height: 6,
                fill: "red",
                stroke: "blue",
                strokeWidth: 0,
                strokeDashArray: null,
                strokeLineCap: "butt",
                strokeDashOffset: 0,
                strokeLineJoin: "miter",
                strokeMiterLimit: 4,
                scaleX: 1,
                scaleY: 1,
                angle: 0,
                flipX: false,
                flipY: false,
                opacity: 0.3,
                shadow: null,
                visible: true,
                clipTo: null,
                backgroundColor: "",
                fillRule: "nonzero",
                paintFirst: "fill",
                globalCompositeOperation: "source-over",
                transformMatrix: null,
                skewX: 0,
                skewY: 0,
                radius: 3,
                startAngle: 0,
                endAngle: 6.283185307179586,
                name: "",
                hotspot: true,
                hasControls: false,
                hasBorders: true,
                perPixelTargetFind: false,
                selectable: true,
                centeredScaling: false,
                label: ""
              }
            ],
            attr: {
              mrid: {
                value: "",
                name: "标识",
                description: ""
              },
              name: {
                value: "终止杆",
                name: "名称",
                description: ""
              },
              pathname: {
                value: "",
                name: "标准带路径全名",
                description: ""
              },
              type: {
                value: "",
                name: "断路器类型",
                description: ""
              },
              inode: {
                value: "",
                name: "物理连接节点1",
                description: ""
              },
              jnode: {
                value: "",
                name: "物理连接节点2",
                description: ""
              },
              substation: {
                value: "",
                name: "所属厂站",
                description: ""
              },
              basevoltage: {
                value: "",
                name: "所属电压类型",
                description: ""
              },
              voltagelevel: {
                value: "",
                name: "所属电压等级",
                description: ""
              },
              bay: {
                value: "",
                name: "所属间隔标识",
                description: ""
              },
              feeder: {
                value: "",
                name: "所属馈线标识",
                description: ""
              },
              status: {
                value: "",
                name: "状态",
                description: ""
              },
              mvarating: {
                value: "",
                name: "遮断容量",
                description: ""
              },
              regionid: {
                value: "",
                name: "区域id",
                description: ""
              },
              normalstatus: {
                value: "",
                name: "正常状态",
                description: ""
              },
              typecode: {
                value: "",
                name: "类型编码",
                description: ""
              },
              engcode: {
                value: "",
                name: "英文编码",
                description: ""
              },
              p: {
                value: "",
                name: "有功",
                description: ""
              },
              q: {
                value: "",
                name: "无功",
                description: ""
              },
              i: {
                value: "",
                name: "电流",
                description: ""
              },
              la: {
                value: "",
                name: "A相电流",
                description: ""
              },
              lb: {
                value: "",
                name: "B相电流",
                description: ""
              },
              lc: {
                value: "",
                name: "C相电流",
                description: ""
              },
              pf: {
                value: "",
                name: "功率因素",
                description: ""
              }
            },
            name: "终止杆"
          };
          let device = createdevice(stopDevice),
            point;
          // getcolone(stopDevice,)
          device.clone(function(cloned) {
            device = cloned;
          }, exportlist);
          point = getpoint.call(Edeg, type);
          device.set({
            top: point.y,
            left: point.x,
            lockScalingX: true,
            lockScalingY: true
          });
          device.set("label", "终止杆");
          Edeg.canvas.add(device);
          Edeg[type] = device;
          return dGroup(Edeg, type);
        }
        function dGroup(Edeg, type) {
          function correct(Edeg, type) {
            let _that = Edeg[type] && gethotpost.call(Edeg[type]);
            let point = getpoint.call(Edeg, type);
            point = cal(_that, point)[0];
            Edeg[type].hotpotslist[point.name].push(Edeg);
            point = point.point;
            setpoint.call(Edeg, point, type);
            Edeg.canvas && Edeg.canvas.renderAll();
          }
          return correct(Edeg, type);
        }
        function createEdge(point1, point2) {
          let line = new fabric.Line([point1.x, point1.y, point2.x, point2.y], {
            fill: "red",
            stroke: "red",
            strokeWidth: 2,
            angle: 0,
            name: "",
            evented: true,
            opacity: 1,
            visible: true,
            cacheWidth: 0,
            cacheHeight: 0,
            scaleX: 1,
            scaleY: 1,
            hasControls: false,
            hasBorders: false,
            perPixelTargetFind: true,
            selectable: false,
            padding: 2
          });
          return line;
        }
        function dLine(Edeg, type) {
          var stopDevice = {
            version: "2.5.0",
            objects: [
              {
                type: "circle",
                version: "2.5.0",
                originX: "left",
                originY: "top",
                left: 20,
                top: 20,
                width: 12,
                height: 12,
                fill: "red",
                stroke: "blue",
                strokeWidth: 0,
                strokeDashArray: null,
                strokeLineCap: "butt",
                strokeDashOffset: 0,
                strokeLineJoin: "miter",
                strokeMiterLimit: 4,
                scaleX: 1,
                scaleY: 1,
                angle: 0,
                flipX: false,
                flipY: false,
                opacity: 1,
                shadow: null,
                visible: false,
                clipTo: null,
                backgroundColor: "",
                fillRule: "nonzero",
                paintFirst: "fill",
                globalCompositeOperation: "source-over",
                transformMatrix: null,
                skewX: 0,
                skewY: 0,
                radius: 6,
                startAngle: 0,
                endAngle: 6.283185307179586,
                name: "",
                hasControls: true,
                hasBorders: true,
                perPixelTargetFind: false,
                selectable: true
              },
              {
                type: "circle",
                version: "2.5.0",
                originX: "left",
                originY: "top",
                left: 24,
                top: 24,
                width: 4,
                height: 4,
                fill: "red",
                stroke: "blue",
                strokeWidth: 0,
                strokeDashArray: null,
                strokeLineCap: "butt",
                strokeDashOffset: 0,
                strokeLineJoin: "miter",
                strokeMiterLimit: 4,
                scaleX: 1,
                scaleY: 1,
                angle: 0,
                flipX: false,
                flipY: false,
                opacity: 0.3,
                shadow: null,
                visible: true,
                clipTo: null,
                backgroundColor: "",
                fillRule: "nonzero",
                paintFirst: "fill",
                globalCompositeOperation: "source-over",
                transformMatrix: null,
                skewX: 0,
                skewY: 0,
                radius: 2,
                startAngle: 0,
                endAngle: 6.283185307179586,
                name: "",
                hotspot: true,
                hasControls: false,
                hasBorders: true,
                perPixelTargetFind: false,
                selectable: true
              }
            ],
            attr: {
              mrid: {
                value: "",
                name: "标识",
                description: ""
              },
              name: {
                value: "空接杆塔",
                name: "名称",
                description: ""
              },
              pathname: {
                value: "",
                name: "标准带路径全名",
                description: ""
              },
              type: {
                value: "",
                name: "断路器类型",
                description: ""
              },
              inode: {
                value: "",
                name: "物理连接节点1",
                description: ""
              },
              jnode: {
                value: "",
                name: "物理连接节点2",
                description: ""
              },
              substation: {
                value: "",
                name: "所属厂站",
                description: ""
              },
              basevoltage: {
                value: "",
                name: "所属电压类型",
                description: ""
              },
              voltagelevel: {
                value: "",
                name: "所属电压等级",
                description: ""
              },
              bay: {
                value: "",
                name: "所属间隔标识",
                description: ""
              },
              feeder: {
                value: "",
                name: "所属馈线标识",
                description: ""
              },
              status: {
                value: "",
                name: "状态",
                description: ""
              },
              mvarating: {
                value: "",
                name: "遮断容量",
                description: ""
              },
              regionid: {
                value: "",
                name: "区域id",
                description: ""
              },
              normalstatus: {
                value: "",
                name: "正常状态",
                description: ""
              },
              typecode: {
                value: "",
                name: "类型编码",
                description: ""
              },
              engcode: {
                value: "",
                name: "英文编码",
                description: ""
              },
              p: {
                value: "",
                name: "有功",
                description: ""
              },
              q: {
                value: "",
                name: "无功",
                description: ""
              },
              i: {
                value: "",
                name: "电流",
                description: ""
              },
              la: {
                value: "",
                name: "A相电流",
                description: ""
              },
              lb: {
                value: "",
                name: "B相电流",
                description: ""
              },
              lc: {
                value: "",
                name: "C相电流",
                description: ""
              },
              pf: {
                value: "",
                name: "功率因素",
                description: ""
              }
            },
            name: "杆"
          };
          let device = createdevice(stopDevice),
            point;
          device.clone(function(cloned) {
            device = cloned;
          }, exportlist);
          const Line = Edeg[type];
          const source = Line.source;
          const target = Line.target;
          Edeg.canvas.add(device);
          point = getpoint.call(Edeg, type);
          device.set({
            top: point.y,
            left: point.x,
            lockScalingX: true,
            lockScalingY: true
          });
          const line1 = createEdge(
            getpoint.call(Line, "source"),
            device.getCenterPoint()
          );
          const line2 = createEdge(
            device.getCenterPoint(),
            getpoint.call(Line, "target")
          );
          Edeg.canvas.add(line1);
          Edeg.canvas.add(line2);
          Edeg[type] = device;
          line1.source = source;
          line1.target = device;
          line2.source = device;
          line2.target = target;
          Edeg.canvas.remove(Line);
          dGroup(line1, "source");
          dGroup(line1, "target");
          dGroup(line2, "source");
          dGroup(line2, "target");
          dGroup(Edeg, type);
        }
        //判断连接类型执行必要的操作
        var edgeTypeList = [
          {
            testfn() {
              //当要连接的设备等于自己或者没有设备时添加终止杆
              return !this[type] || this[type] === this;
            },
            executefn() {
              return Dstop(this, type);
            }
          },
          {
            testfn() {
              return this[type] instanceof fabric.Group;
            },
            executefn() {
              return dGroup(this, type);
            }
          },
          {
            testfn() {
              return this[type] instanceof fabric.Line;
            },
            executefn() {
              return dLine(this, type);
            }
          }
        ];
        return edgeTypeList.some(item => {
          if (item.testfn.call(that, type)) {
            return item.executefn.call(that, type);
          }
        });
      }
      function sethotpots(Edeg) {
        setLine.call(Edeg, "source");
        setLine.call(Edeg, "target");
        return Edeg.canvas && Edeg.canvas.renderAll();
      }

      canvas.maskCanvas.on("object:moving", function(e) {
        let target = e.target;

        target._sourcelist &&
          target._sourcelist.forEach(element => {
            element.set({ x1: e.pointer.x, y1: e.pointer.y });
            canvas.renderAll();
          });
        target._targetlist &&
          target._targetlist.forEach(element => {
            element.set({ x2: e.pointer.x, y2: e.pointer.y });

            canvas.renderAll();
          });
        canvas.renderAll();
      });
      canvas.maskCanvas.on("object:moved", function(e) {
        let p = e.target;
        p._targetlist &&
          p._targetlist.forEach(function(item) {
            let target = canvas.findTarget(e.e);
            if (target !== item.target) {
              item.target && delete item.target.source;
              item.target = target;
            }
          });
        p._sourcelist &&
          p._sourcelist.forEach(function(item) {
            let source = canvas.findTarget(e.e);
            if (source !== item.source) {
              item.source && delete item.source.target;
              item.source = source;
              if (source) {
                source._sourcelist = source._sourcelist || [];
                source._sourcelist.push(item);
              }
            }
          });
        canvas.renderAll();
      });
      interactive.prototype.addnewdrawtype("edge1", function() {
        let that = this;
        let _drawOptions = that._drawOptions;
        let _style = that._style;
        let x = _drawOptions._start.x;
        let y = _drawOptions._start.y;
        let fill = _style.fill;
        let stroke = _style.stroke;
        let strokeWidth = _style.strokeWidth;
        var line = new ShPolyline([_drawOptions._start, _drawOptions._start], {
          fill: stroke,
          stroke: fill,
          strokeWidth: strokeWidth,
          angle: 0,
          name: "",
          evented: true,
          opacity: 1,
          visible: true,
          cacheWidth: 0,
          cacheHeight: 0,
          scaleX: 1,
          scaleY: 1,
          hasControls: false,
          hasBorders: false,
          perPixelTargetFind: true,
          selectable: false,
          padding: 2
        });
        that.root.add(line);
        let canvas = that.root.root;
        let e = window.event;
        let target = canvas.findTarget(e);
        // if (target) {
        //   target._sourcelist = target._sourcelist || [];
        //   target._sourcelist.push(line);
        // }

        line.source = target;
        _drawOptions._drawingobj = {
          target: line,
          t: null,
          draw: function(start, end) {
            let canvas = that.root.root;
            let target = canvas.findTarget(end.e);
            if (!this.t) {
              this.t = target;
            }
            // 该段代码是在鼠标经过时提示出可以连接的连线点，建议放在对呀的元素内处理
            // if (this.t != target) {
            //   this.t._objects.forEach(item => {
            //     if (item.hotspot) {
            //       item.set("fill", "red");
            //       canvas.renderAll();
            //     }
            //   });
            //   this.t = target;
            // }
            // if (target && target instanceof fabric.Group) {
            //   target._objects.forEach(item => {
            //     if (item.hotspot) {
            //       item.set("fill", "green");
            //       canvas.renderAll();
            //     }
            //   });
            // }
            end = end.absolutePointer;
            this.target.points.pop();
            this.target.points.push(end);
            // this.target.set({ x2: end.x, y2: end.y });
            that.root.renderAll();
          },
          drawend: function(start, end) {
            this.target.setCoords();
            let canvas = that.root.root;
            that.root.fire("add", { target: this.target });
            that.root.fire("drawend", {
              target: this.target
            });
            that.root.selection = true;
            that._drawOptions.drawtype = null;
            // if (this.t) {
            //   let p = this.t;
            //   p._targetlist = p._targetlist || [];
            //   p._targetlist.push(this.target);
            // }
            this.target.target = this.t;
            this.t = null;
            that._drawOptions._start = null;
            // that.canvas.renderAll()
            that._drawOptions._drawingobj = null;
            sethotpots(this.target, e);
          }
        };
      });
      interactive.prototype.addnewdrawtype("edge", function() {
        let that = this;
        let _drawOptions = that._drawOptions;
        let _style = that._style;
        let x = _drawOptions._start.x;
        let y = _drawOptions._start.y;
        let fill = _style.fill;
        let stroke = _style.stroke;
        let strokeWidth = _style.strokeWidth;
        var line = new fabric.Line([x, y, x, y], {
          fill: stroke,
          stroke: fill,
          strokeWidth: strokeWidth,
          angle: 0,
          name: "",
          evented: true,
          opacity: 1,
          visible: true,
          cacheWidth: 0,
          cacheHeight: 0,
          scaleX: 1,
          scaleY: 1,
          hasControls: false,
          hasBorders: false,
          perPixelTargetFind: true,
          selectable: false,
          padding: 2
        });
        that.root.add(line);
        let canvas = that.root.root;
        let e = window.event;
        let target = canvas.findTarget(e);
        // if (target) {
        //   target._sourcelist = target._sourcelist || [];
        //   target._sourcelist.push(line);
        // }
        line.source = target;
        _drawOptions._drawingobj = {
          target: line,
          t: null,
          draw: function(start, end) {
            let canvas = that.root.root;
            let target = canvas.findTarget(end.e);
            if (!this.t || this.t !== target) {
              this.t = target;
            }
            // 该段代码是在鼠标经过时提示出可以连接的连线点，建议放在对呀的元素内处理
            // if (this.t != target&& target instanceof fabric.Group) {
            //   this.t._objects.forEach(item => {
            //     if (item.hotspot) {
            //       item.set("fill", "red");
            //       canvas.renderAll();
            //     }
            //   });
            //   this.t = target;
            // }
            // if (target && target instanceof fabric.Group) {
            //   target._objects.forEach(item => {
            //     if (item.hotspot) {
            //       item.set("fill", "green");
            //       canvas.renderAll();
            //     }
            //   });
            // }
            end = end.absolutePointer;
            this.target.set({ x2: end.x, y2: end.y });
            that.root.renderAll();
          },
          drawend: function(start, end) {
            this.target.setCoords();
            let canvas = that.root.root;
            that.root.fire("add", { target: this.target });
            that.root.fire("drawend", {
              target: this.target
            });
            that.root.selection = true;
            that._drawOptions.drawtype = null;
            // if (this.t) {
            //   let p = this.t;
            //   p._targetlist = p._targetlist || [];
            //   p._targetlist.push(this.target);
            // }
            this.target.target = this.t;
            this.t = null;
            that._drawOptions._start = null;
            // that.canvas.renderAll()
            that._drawOptions._drawingobj = null;
            sethotpots(this.target);
          }
        };
      });
      canvas.on("mouse:dblclick", function(e) {
        let target = canvas.findTarget(e.e);
        if (target instanceof fabric.Line) {
          canvas.drawStart();
          var rect1 = new fabric.Rect({
            top: target.y1 - 5,
            left: target.x1 - 5,
            width: 10,
            height: 10,
            hasControls: false,
            hasBorders: true,
            fill: "blue",
            stroke: "green",
            strokeWidth: 0,
            _sourcelist: [target]
          });
          var rect2 = new fabric.Rect({
            top: target.y2 - 5,
            left: target.x2 - 5,
            width: 10,
            height: 10,
            hasControls: false,
            hasBorders: true,
            fill: "blue",
            stroke: "green",
            strokeWidth: 0,
            _targetlist: [target]
          });
          canvas.maskCanvas.add(rect1);
          canvas.maskCanvas.add(rect2);
        }
      });
      canvas.maskCanvas.on("mouse:dblclick", function(e) {
        if (!e.target) {
          sethotpots(canvas.maskCanvas._objects[0]._sourcelist[0]);
          canvas.drawEnd();
          canvas.maskCanvas.clear();
        }
      });
      //fabric自己封装了event事件，后面可以不需要记录，使用内置方法Canvas.getPointer
      //   canvas.on("mouse:down", function(e) {
      //     console.log(12);
      //   });
      this.$refs.canvasparents.addEventListener("dragover", event => {
        event.preventDefault();
        return;
      });
      this.$refs.canvasparents.addEventListener("drop", event => {
        event.preventDefault();
        let name = event.dataTransfer.getData("name");
        let device = getcolone(devicelist, name, exportlist);
        device.set({
          top: canvas.getPointer(event).y,
          left: canvas.getPointer(event).x,
          label: name,
          lockScalingX: true,
          lockScalingY: true
        });
        canvas.add(device);
        device.setCoords();
      });
    });
    function getcolone(devicelist, name, exportlist) {
      let device;
      devicelist[name].clone(function(cloned) {
        device = cloned;
      }, exportlist);
      return device;
    }
    // window.devicelist = devicelist;
    deviceloader(alldevice);
    maploader(allmap);
  }
};
</script>

